﻿#include "userrelationservice.h"
#include <QMessageBox>
#include "dbhelper.h"
#include <QFileDialog>
#include "mymessagebox.h"

UserRelationService::UserRelationService(QObject *parent) : QObject(parent)
{

}

void UserRelationService::queryPlatformUser(QWidget *widget, QString username, QString companyId)
{
    if(username.isEmpty() || companyId.isEmpty()){
        QMessageBox::warning(widget, "警告", "查询信息不能为空！");
        return;
    }

    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        QJsonObject userObj = data.value("user").toObject();
        QJsonObject companyObj = data.value("company").toObject();
        User user;
        user.loadFromJsonObject(userObj);
        Company company;
        company.loadFromJsonObject(companyObj);
        QMessageBox::information(widget, "信息", message);
        emit queryPlatformUserSuccess(user, company);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->queryPlatformUser(username, companyId);
}

void UserRelationService::addPlatformUser(
        QWidget *widget,
        QPushButton *button,
        QString targetUsername,
        UserRelation::RelationType type)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        Tools::setButtonState(button, true);
        QMessageBox::information(widget, "信息", message);
        widget->close();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        Tools::setButtonState(button, true);
        QMessageBox::warning(widget, "警告", message);
        emit addPlatformUserFailed();
    });

    Tools::setButtonState(button, false);
    manager->addPlatformUser(User::getUsername(), targetUsername, type);
}

void UserRelationService::updateUserRelationData(QWidget *widget, UserRelation::RelationType type)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        Q_UNUSED(message);
        QJsonArray relationArr = data.value("relations").toArray();
        DbHelper helper;
        helper.clearUserRelationByType(type);
        QList<UserRelation*> relations;
        for(QJsonValue obj:relationArr){
            UserRelation *relation = new UserRelation();
            relation->loadFromJsonObject(obj.toObject());
            helper.insertUserRelation(*relation);
            relations.append(relation);
        }

        emit this->updateUserRelationDataSuccess(relations);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
        emit addPlatformUserFailed();
    });

    manager->getUserRelations(User::getUsername(), type);
}

void UserRelationService::queryUserRelation(
        UserManageTableView *tableView,
        UserManageTreeView *treeView,
        bool isShowPlatformUser,
        QString overallQuery,
        QString nickNameQuery,
        QString contactQuery,
        QString telQuery)
{
    QStandardItem *selectedItem = treeView->selectedItem();

    if(selectedItem != nullptr){

    }else{
        qDebug()<<"未选择";
    }

    QString primaryDirectory = treeView->selectedPrimaryDirectory();
    QString secondaryDirectory = treeView->selectedSecondaryDirectory();

    qDebug()<<"一级类目："<<primaryDirectory.toUtf8().data();
    qDebug()<<"二级类目："<<secondaryDirectory.toUtf8().data();

    tableView->queryUserRelation(
                isShowPlatformUser,
                overallQuery,
                nickNameQuery,
                contactQuery,
                telQuery,
                primaryDirectory,
                secondaryDirectory);
}

void UserRelationService::addNonPlatformUser(
        QWidget *widget,
        QPushButton *button,
        UserRelation::RelationType type,
        QString nickName,
        QString contact,
        QString tel,
        QString remark,
        QString primaryDirectory,
        QString secondaryDirectory)
{
    if(nickName.isEmpty() || contact.isEmpty())
    {
        QMessageBox::warning(widget, "警告", "客户名称和联系人不能为空！");
        return;
    }

    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        Tools::setButtonState(button, true);
        QMessageBox::information(widget, "信息", message);
        widget->close();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        Tools::setButtonState(button, true);
        QMessageBox::warning(widget, "警告", message);
    });

    Tools::setButtonState(button, false);
    manager->addNonPlatformUser(
                User::getUsername(),
                type,
                nickName,
                contact,
                tel,
                remark,
                primaryDirectory,
                secondaryDirectory);
}

void UserRelationService::queryUserRelationDetail(QWidget *widget, QString username, QString companyId)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        Q_UNUSED(message);
        QJsonObject userObj = data.value("user").toObject();
        QJsonObject companyObj = data.value("company").toObject();
        User user;
        user.loadFromJsonObject(userObj);
        Company company;
        company.loadFromJsonObject(companyObj);
        emit queryUserRelationDetailSuccess(user, company);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->queryUserRelationDetail(username,companyId);
}

void UserRelationService::buildSubAccount(QWidget *widget, QString targetUsername, UserRelation::RelationType type)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        QMessageBox::information(widget, "信息", message);
        emit buildSubAccountSuccess();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->buildSubAccount(User::getUsername(), targetUsername, type);
}

void UserRelationService::changeUserRelation(QWidget *widget, QString targetUsername, UserRelation::RelationType type)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        QMessageBox::information(widget, "信息", message);
        emit changeUserRelationSuccess();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->changeUserRelation(User::getUsername(), targetUsername, type);
}

void UserRelationService::updateUserRelation(
        QWidget *widget,
        QString targetUsername,
        UserRelation::RelationType type,
        QString urClientName,
        QString urContact,
        QString urTel,
        QString urRemark,
        QString urCredit,
        QString urPrimaryDirectory,
        QString urSecondaryDirectory,
        QString userNickName,
        QString userPosition,
        QString userTel,
        QString userMobile,
        QString userQQ,
        QString userWechat,
        QString companyCompanyName,
        QString companyContact,
        QString companyTel,
        QString companyFax,
        QString companyWebsite,
        QString companyEmail,
        QString companyProvince,
        QString companyCity,
        QString companyDistrict,
        QString companyAddress,
        QString companyAccount,
        QString companyIntroduction,
        QString companyTicketCompanyName,
        QString companyTaxNum,
        QString companyBank,
        QString companyTicketAccount,
        QString companyTicketTel,
        QString companyTicketAddress)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        QMessageBox::information(widget, "信息", message);
        widget->close();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->updateUserRelation(
                User::getUsername(),
                targetUsername,
                type,
                urClientName,
                urContact,
                urTel,
                urRemark,
                urCredit,
                urPrimaryDirectory,
                urSecondaryDirectory,
                userNickName,
                userPosition,
                userTel,
                userMobile,
                userQQ,
                userWechat,
                companyCompanyName,
                companyContact,
                companyTel,
                companyFax,
                companyWebsite,
                companyEmail,
                companyProvince,
                companyCity,
                companyDistrict,
                companyAddress,
                companyAccount,
                companyIntroduction,
                companyTicketCompanyName,
                companyTaxNum,
                companyBank,
                companyTicketAccount,
                companyTicketTel,
                companyTicketAddress);
}

void UserRelationService::uploadUserRelation(QWidget *widget, UserRelation::RelationType type, QList<UserRelation*> relations)
{
    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        Q_UNUSED(message);
        emit this->uploadUserRelationSuccess();
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->uploadUserRelation(User::getUsername(), type, relations);
}

bool UserRelationService::checkDataHeader(UserRelation::RelationType type, QList<QVariant> header)
{
    if(header.size() != 6){
        MyMessageBox::warning("警告", QString("表头项数为6，输入表头项长度为%1！").arg(header.size()));
        return false;
    }

    QStringList correctHeader={
        "客户名称",
        "联系人",
        "电话",
        "备注",
        "一级类别",
        "二级类别"
    };

    if(type == UserRelation::Giver){
        correctHeader[0] = "供应商名称";
    }

    int index = -1;
    for(int i=0; i<header.size(); i++)
    {
        if(header[i] != correctHeader[i]){
            index = i;
            break;
        }
    }

    if(index != -1){
        MyMessageBox::warning("警告", QString("表头项%1错误，检测到的表头项为：%2 正确表头项为：%3")
                           .arg(index+1).
                           arg(header[index].toString()).
                           arg(correctHeader[index]));
        return false;
    }

    return true;
}

UserRelation* UserRelationService::checkData(UserRelation::RelationType type, int index, QList<QVariant> dataItem){
    UserRelation *relation = new UserRelation();

    relation->nickName = dataItem[0].toString();
    relation->contact = dataItem[1].toString();
    relation->tel = dataItem[2].toString();
    relation->remark = dataItem[3].toString();
    relation->primaryDirectory = dataItem[4].toString();
    relation->secondaryDirectory = dataItem[5].toString();

    QString name = (type==UserRelation::Client)?"客户名称":"供应商名称";

    if(relation->nickName.isEmpty() || relation->contact.isEmpty()){
        MyMessageBox::warning("警告", QString("第%1条数据错误，错误提示：%2和联系人不能为空！").
                           arg(index).
                           arg(name));
        return nullptr;
    }

    return relation;
}

QList<UserRelation*> UserRelationService::checkData(UserRelation::RelationType type, QList<QList<QVariant>> data)
{
    QList<UserRelation*> relations;

    for(int i=1; i<data.size(); i++){
        UserRelation *relation = checkData(type, i, data.at(i));
        if(relation == nullptr){
            break;
        }
        relations.append(relation);
    }

    return relations;
}

void UserRelationService::adjustUserRelationFinance(
        QWidget *widget,
        QPushButton *button,
        UserRelation *relation,
        QString relatedMessageId,
        double ticketValue,
        double moneyValue){
    if(relation == nullptr){
        QMessageBox::warning(widget, "警告", "未选择客户或供应商！");
        return;
    }

    if(ticketValue==0.0 && moneyValue==0.0){
        QMessageBox::warning(widget, "警告", "调整金额不能全为0！");
        return;
    }

    double ticketIn, ticketOut, moneyIn, moneyOut;
    if(relation->type == UserRelation::Client || relation->type-2==UserRelation::Client){
        ticketIn = 0;
        ticketOut = ticketValue;
        moneyIn = moneyValue;
        moneyOut = 0;
    }else{
        ticketIn = ticketValue;
        ticketOut = 0;
        moneyIn = 0;
        moneyOut = moneyValue;
    }

    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        button->setEnabled(true);
        emit this->adjustUserRelationFinanceSuccess();
        QMessageBox::information(widget, "信息", message);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        button->setEnabled(true);
        QMessageBox::warning(widget, "警告", message);
    });

    button->setEnabled(false);
    manager->adjustUserRelationFinance(
                relation->sourceUsername,
                relation->targetUsername,
                relatedMessageId,
                relation->type,
                relation->ticketIn,
                relation->ticketOut,
                relation->moneyIn,
                relation->moneyOut,
                ticketIn,
                ticketOut,
                moneyIn,
                moneyOut);
}

void UserRelationService::deleteUserRelation(
        QWidget *widget,
        UserRelation *relation){
    if(relation == nullptr){
        QMessageBox::warning(widget, "警告", "客户或供应商信息不存在！");
        return;
    }

    manager = new UserRelationNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    connect(manager, &BaseNetworkAccessManager::onSuccess,
            [=](QString message)
    {
        QMessageBox::information(widget, "信息", message);
        widget->close();
    });

    manager->deleteUserRelation(relation->sourceUsername, relation->targetUsername, relation->type);
}
